<?php
//微信公众号的输入三位验证码处理
/**
  * wechat php test
  */
header("content-type:text/html;charset=utf8");
//define your token
define("TOKEN", "hispot");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        //接收微信公众号那边传递过来的参数
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        //判断值是否为空
        if (!empty($postStr)){
            //将xml的数据格式转换为Obj的数据格式
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            //向微信推送消息时的数据格式
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>"; 
             //关注回复文本信息
            if ($postObj->Event == 'subscribe') {
                $contentStr = "欢迎关注HiSpot嗨镜，我们将为你提供良好的服务";
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
                die;
            }else if($postObj->Event == "CLICK"){
			$contentStr = '请用微信扫描包装盒内的二维码或直接回复设备屏幕上显示的三位数字以完成设备绑定';
			$msgType = "text";
                        $resultStr = sprintf ( $textTpl , $fromUsername , $toUsername , $time , $msgType , $contentStr );
                        echo $resultStr;
			die;
           }            
            if(!empty( $keyword ))
            {
                $contentStr = $this->verification($keyword,$fromUsername);
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo "Input something......";
            }
        }else {
            echo "";
            exit;
        }
    }

    //设备绑定的方法
    public function verification($keyword,$fromUsername){
        //连接数据库
        $pdo = new PDO('mysql:host=123.57.16.97;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
       
        //设置字符集
        $pdo->exec('set names utf8');
       
        //查询三位验证码登录表中是否存在数据
        $select_interim = "SELECT * FROM interim WHERE random = ".$keyword;
        $random_data = $pdo->query($select_interim)->fetch(PDO::FETCH_ASSOC);
        if (empty($random_data)) {
            return "验证码不存在或者验证码超时，请在设备端重新发起";
        }
       
        //查询此SN号是否被绑定过   绑定过将之前的进行删除
        $select_binding = "SELECT * FROM binding WHERE device_sn = '".$random_data['device_sn']."'";
        $binding_data = $pdo->query($select_binding)->fetch(PDO::FETCH_ASSOC);
        if (!empty($binding_data)) {
            $delete_binding = "DELETE FROM binding WHERE device_sn = '".$binding_data['device_sn']."'";
            $pdo->exec($delete_binding);
        }
       
        //判断三位验证码登录表中的数据是否过期
        if ($random_data['found_time']+300 > time()) {
            
            //满足一切条件，将此微信号与SN号绑定存入binding表中
            $insert_binding = "INSERT INTO binding(openid,device_sn,`time`) VALUES('".$fromUsername."','".$random_data['device_sn']."','".time()."')";
            if ($pdo->exec($insert_binding)) {
            
                //存入binding表中之后查询此微信用户是否绑定过账户
               $select_user = "SELECT * FROM user WHERE openid = '".$fromUsername."'";
               $user_data = $pdo->query($select_user)->fetch(PDO::FETCH_ASSOC);
            
               //绑定过账户通知用户绑定成功   未绑定过通知用户只差一步完成绑定
               if (empty($user_data)) {
                    $delete_sql = "DELETE FROM interim WHERE device_sn = '".$random_data['device_sn']."'";
                    $pdo->exec($delete_sql);
                    return "只差一步，完成绑定，<a href=\"https://pay.hispot.cn/gitscan/h5/login.php?openid=".$fromUsername."\">点击这里哦</a>";
               }else{
                    $delete_sql = "DELETE FROM interim WHERE device_sn = '".$random_data['device_sn']."'";
                    $pdo->exec($delete_sql);
                    $this->data_synchro_old_database($user_data,$fromUsername,$pdo);
                    file_get_contents("https://pay.hispot.cn/gitscan/pushLoginInfo.php?openid=".$fromUsername);
                    file_put_contents("./push.log",$fromUsername.'@'.date('Y-m-d H:i:s').'微信登录'.PHP_EOL,FILE_APPEND);
                    return "绑定成功，请于24小时前往设备端进行登录";
               }
            
            //将此微信号与SN号入库失败时，告知用户请重试
            }else{
                return "网络请求错误，请再试一次";
            }

        //验证码过期告知用户已过期
        }else{
            $delete_sql = "DELETE FROM interim WHERE device_sn = '".$random_data['device_sn']."'";
            $pdo->exec($delete_sql);
            return "验证码超时，请在设备端重新发起";
        }
    }

    //验证token值是否正确
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function data_synchro_old_database($user_data,$openid,$pdo){
        //将新登录的信息同步到旧数据库中的登录信息表
        $pdo_user_old = $this->pdo_connect_old_user_database();
        $tel = $user_data['tel'];
        //旧数据库中存在此号码的数据进行删除
        $sql = "SELECT * FROM uc_members WHERE username = '$tel'";
        $data = $pdo_user_old->query($sql)->fetch(PDO::FETCH_ASSOC);
        if ($data) {
            // $delete_sql = "DELETE FROM uc_members WHERE username = '$tel'";
            // $pdo_user_old->exec($delete_sql);
            $uid = $data['uid'];
        }else{
            $password = $user_data['password'];
            $salt = substr(md5(rand('1','1000')),0,6);
            $old_password = md5($password.$salt);
            $insert_old_user_sql = "INSERT INTO uc_members(username,password,salt,phone) VALUES('$tel','$old_password','$salt','$tel')";
            $pdo_user_old->exec($insert_old_user_sql);
            $uid = $pdo_user_old->lastInsertId();
        }

        //获取新数据库中的绑定信息
        $select_binding_sql = "SELECT * FROM binding WHERE openid = '$openid' ORDER BY b_id DESC";
        $new_binding_data = $pdo->query($select_binding_sql)->fetch(PDO::FETCH_ASSOC);
            // file_put_contents("./data.log",$new_binding_data);

        //将新数据的绑定信息同步旧数据库的绑定信息表中
        $pdo_binding_old = $this->pdo_connect_old_binidng_database();
        $sn = $new_binding_data['device_sn'];
        $time = date("Y-m-d H:i:s");
        $select_old_binding_sql = "SELECT * FROM weixin_binging WHERE Uid = '$uid' AND OpinID = '$openid' AND DeviceSelf = '$sn'";
        $old_binding_data = $pdo_binding_old->query($select_old_binding_sql)->fetch(PDO::FETCH_ASSOC);
        if (!$old_binding_data) {
            $insert_old_binidng_sql = "INSERT INTO weixin_binging(Uid,OpinID,CreateTime,DeviceSelf) VALUES('$uid','$openid','$time','$sn')";
            $pdo_binding_old->exec($insert_old_binidng_sql);   
        }

        //最后将uid和openid关联添加weixin_user表中 添加之前先通过uid以及openid来查询关联数据是否已经存在
        $select_relation_data_sql = "SELECT * FROM weixin_user WHERE openId = '$openid' AND user = '$uid'";
        $relation_data = $pdo_binding_old->query($select_relation_data_sql)->fetch(PDO::FETCH_ASSOC);
        //如果数据不存在
        if (!$relation_data) {
            //将uid和openid关联存在weixin_user表中
            $insert_old_relation_sql = "INSERT INTO weixin_user(openId,user) VALUES('$openid','$uid')";
            $pdo_binding_old->exec($insert_old_relation_sql); 
        }
    }

    //pdo连接旧用户登录信息库
    function pdo_connect_old_user_database(){
        $pdo_user_old = new PDO('mysql:host=123.57.16.97;dbname=ucenter','root','zqVnUy6cxsQXbpEZ');
        $pdo_user_old->exec('set names utf8'); 
        return $pdo_user_old;
    }

    //pdo连接旧用户绑定表
    function pdo_connect_old_binidng_database(){
        $pdo_binding_old = new PDO('mysql:host=123.57.16.97;dbname=wx_online_movie','root','zqVnUy6cxsQXbpEZ');
        $pdo_binding_old->exec('set names utf8');
        return $pdo_binding_old;
    }
}

?>
